package com.itheima.chapter03.controller;

import com.itheima.chapter03.domain.Article;
import com.itheima.chapter03.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

//@Controller     // 下面的方法，返回都是字符串，指向页面地址，理解成网址
@RestController  // === @Controller + @ResponseBody
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @GetMapping
    public AjaxResult list() {
//        List<Article> articleList = articleService.list();
//        AjaxResult ajaxResult = AjaxResult.success(articleList);
//        return ajaxResult;
        return AjaxResult.success(articleService.list());
    }

    @PostMapping
    public AjaxResult insert(@RequestBody Article article) {
        int ret = articleService.insert(article);
        if (ret > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    // RESTfull风格
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Integer articleId) {
        int ret = articleService.delete(articleId);
        if (ret > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable Integer id) {
        Article article = articleService.get(id);
        if (article != null) {
            return AjaxResult.success(article);
        } else {
            return AjaxResult.error("没有找到");
        }
    }
}